package com.chebaohui.iqs.service.impl.deal.union.profess;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.chebaohui.iqs.service.impl.ChinaUnionServieImpl;
import com.chebaohui.iqs.service.impl.deal.union.entity.Company;
import com.chebaohui.iqs.service.impl.deal.union.sdk.UnionConfig;
import com.chebaohui.iqs.service.impl.deal.union.sdk.UnionSign;
import com.chebaohui.iqs.service.impl.deal.union.util.PayConsume;

/**
 * 银联支付发起-网页
 * 
 * @author xielonghai
 *
 */
public class UnionPrice {
	/**
	 * log:日志输出
	 */
	private static Log log = LogFactory.getLog(UnionPrice.class);

	/**
	 * @param orderSid
	 *            商户订单号
	 * @param txnAmt
	 *            交易金额,单位元
	 * @return
	 */
	public String getPriceHtml(String orderSid, String txnAmt) throws Exception {
		Company company = PayConsume.getCompany(ChinaUnionServieImpl.union_file_path, orderSid, txnAmt);

		Map<String, String> data = PayConsume.getPayData(company);

		/** 请求参数设置完毕，以下对请求参数进行签名并生成html表单，将表单写入浏览器跳转打开银联页面 **///参数签名
		Map<String, String> submitFromData = UnionSign.sign(data, UnionConfig.encoding, company.getUnion());

		/** 获取请求银联的前台地址：对应属性文件acp_sdk.properties文件中的acpsdk.frontTransUrl **/
		String requestFrontUrl = company.getUnion().getFrontRequestUrl();

		/** 生成自动跳转的Html表单 **/
		String fromHtml = createAutoFormHtml(requestFrontUrl, submitFromData, "UTF-8");

		log.info(company.getMerId() + ",请求银联的前台地址:" + requestFrontUrl + ",Html表单:" + fromHtml);
		return fromHtml;
	}

	/**
	 * 功能：前台交易构造HTTP POST自动提交表单<br>
	 * 
	 * @param action
	 *            表单提交地址<br>
	 * @param hiddens
	 *            以MAP形式存储的表单键值<br>
	 * @param encoding
	 *            上送请求报文域encoding字段的值<br>
	 * @return 构造好的HTTP POST交易表单<br>
	 */
	public static String createAutoFormHtml(String reqUrl, Map<String, String> hiddens, String encoding) {
		StringBuffer sf = new StringBuffer();
		sf.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + encoding
				+ "\"/></head><body>");
		sf.append("<form id = \"pay_form\" action=\"" + reqUrl + "\" method=\"post\">");
		if (null != hiddens && 0 != hiddens.size()) {
			Set<Entry<String, String>> set = hiddens.entrySet();
			Iterator<Entry<String, String>> it = set.iterator();
			while (it.hasNext()) {
				Entry<String, String> ey = it.next();
				String key = ey.getKey();
				String value = ey.getValue();
				sf.append("<input type=\"hidden\" name=\"" + key + "\" id=\"" + key + "\" value=\"" + value + "\"/>");
			}
		}
		sf.append("</form>");
		sf.append("</body>");
		sf.append("<script type=\"text/javascript\">");
		sf.append("document.all.pay_form.submit();");
		sf.append("</script>");
		sf.append("</html>");
		return sf.toString();
	}
}
